from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """
    message = "You must be the owner of this object."

    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated

    def has_object_permission(self, request, view, obj):
        # 安全方法则有权限（可查看）
        if request.method in permissions.SAFE_METHODS:
            return True
        # 非安全方法进行校验
        if hasattr(obj, 'job_hunter_id'):
            return obj.job_hunter_id.user_id == request.user.id
        elif hasattr(obj, 'company_id'):
            return obj.company_id.user_id == request.user.id
        return True

